package com.beone.admin.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * redis 相关工具
 *
 * @author Pengyan
 * @date 2018/9/13 9:43
 **/
@Component
public class RedisUtils {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisTemplate redisTemplate;

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        // 序列化设置
        redisTemplate.setDefaultSerializer(new JdkSerializationRedisSerializer());
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // 解决key之前多了一些如 \xAC\xED\x00 的字符问题
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        this.redisTemplate = redisTemplate;
    }

    /**
     * 存储字符串值
     * @param key
     * @param value
     */
    public void setRedisStringValue(String key,String value){
        stringRedisTemplate.opsForValue().set(key,value);
    }

    /**
     * 存储字符串值
     * @param key
     * @param value
     */
    public void setRedisStringValue(String key,String value,long timeoutSeconds){
        stringRedisTemplate.opsForValue().set(key,value, timeoutSeconds, TimeUnit.SECONDS);
    }

    /**
     * 获取字符串值
     * @param key
     * @return
     */
    public String getRedisStringValue(String key){
        return stringRedisTemplate.opsForValue().get(key)==null?"":stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 存储对象
     * @param key
     * @param value
     * @param timeoutSeconds 超时时间（秒）
     */
    public void setRedisObject(String key, Object value, long timeoutSeconds) {
        redisTemplate.opsForValue().set(key, value, timeoutSeconds, TimeUnit.SECONDS);
    }

    /**
     * 获取对象
     * @param key
     * @return
     */
    public Object getRedisObject(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除对象
     * @param key
     */
    public void deleteRedisObject(String key) {
        redisTemplate.delete(key);
    }
}
